import { asyncRoutes, constantRoutes } from '@/router'
import {getRoleMenu }from '@/api/user'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    // console.log(route.meta.roles);
    // console.log(1);
    // console.log(roles);
    // console.log(route);
    // console.log(roles.some(role => route.meta.roles.includes(role)));
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
    //为true,在动态路由中，均有权限，把没有权限的设为可见
  }
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
 export function generaMenu(routes, data) {
  data.forEach(item => {
    // alert(JSON.stringify(item))
    const menu = {
      path: item.menuType === 1 ? item.menuId + '_key' : item.url,
      component: item.menuType === 1 ? Layout : resolve => {
        require(['@/views' + item.url + '/index'], resolve)
      },
      children: [],
      alwaysShow:false,
      name: 'menu_' + item.menuId,
      meta: { title: item.menuName, id: item.menuId }
    }
    if (item.children) {
      generaMenu(menu.children, item.children)
    }
    routes.push(menu)
  })
}


/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes //动态路由
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  // console.log(routes);
  routes.forEach(route => {
    const tmp = { ...route }
    // console.log(tmp)
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  // console.log(res)
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roleId) {

    return new Promise(resolve => {
      let menuList
      let needPage = false
      getRoleMenu(roleId,needPage).then((response)=>{
        menuList = response.obj.list
        const loadMenuData = []
        let accessedRoutes = []
        Object.assign(loadMenuData, menuList)
        // console.log(accessedRoutes)
        generaMenu(accessedRoutes, loadMenuData)
        // console.log(accessedRoutes)
        // if (roles.includes('0')) {
        //   accessedRoutes = asyncRoutes || []
        // } else {
        // accessedRoutes = filterAsyncRoutes(accessedRoutes, roles)
        // }   
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
